﻿using System;
using System.Net.Mail;
using System.IO;

namespace DotNetNexusSpam.SpamFilter
{
    class SpamSuspiciousFilter : FilterBase
    {
        public SpamSuspiciousFilter(CDOMessageWrapper email, string startupPath)
            : base(email, startupPath)
        {
            base.Name = "SuspiciousSpam";
        }

        public override void Fire()
        {
            base.ActionToTake = FilterAction.PROCESS_NORMALLY;
            base.IsSpam = false;

            foreach (string tag in _spamWords)
            {
                if (Email.CDOMessage.TextBody.Contains(tag) ||
                    Email.CDOMessage.HTMLBody.Contains(tag) ||
                    Email.CDOMessage.Subject.Contains(tag) ||
                    Email.CDOMessage.From.Contains(tag) ||
                    Email.CDOMessage.To.Contains(tag)) 
                {
                    base.ActionToTake = FilterAction.ADD_TAG_TO_SUBJECT;
                    base.IsSpam = true;
                    break;
                }
            }
        }

        /// <summary>
        /// Load all words that will be used to flag an email as spam.
        /// </summary>
        private string[] _spamWords;
        private const string SPAM_TAG = "spamTag.txt";
        public override void LoadConfiguration()
        {
            string settingsPath = base.StartupPath + "config\\" + SPAM_TAG;
            if (File.Exists(settingsPath))
            {
                string spamTagContent = "";
                using (StreamReader settingsReader = new StreamReader(settingsPath))
                {
                    spamTagContent = settingsReader.ReadToEnd();
                }
                _spamWords = spamTagContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                _log.Debug("Spam tags file was loaded succesfully.");
            }
            else
            {
                _log.Warn("Spam tags file could not be loaded from " + settingsPath);
            }
        }
    }
}
